<template>
  <div class="user-recharge-container">
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <div class="loading-content">
        <el-icon class="loading-icon"><Loading /></el-icon>
        <p>กำลังโหลดหน้าเติมเงิน...</p>
      </div>
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-result
        icon="error"
        title="โหลดหน้าเว็บไซต์ไม่สำเร็จ"
        :sub-title="error"
      >
        <template #extra>
          <el-button type="primary" @click="loadSessionData">โหลดใหม่อีกครั้ง</el-button>
        </template>
      </el-result>
    </div>

    <!-- 充值表单 -->
    <div v-else class="recharge-form-container">
      <!-- 充值表单 -->
      <div class="recharge-form">

        <el-form
          ref="rechargeFormRef"
          :model="rechargeForm"
          :rules="rechargeRules"
          label-width="0px"
          class="simple-form"
        >
          <!-- 充值金额 -->
          <el-form-item prop="amount" class="amount-form-item">
            <div class="form-section">
              <div class="section-title-wrapper">
                <div class="title-content">
                  <h3 class="section-title">ซื้อเหรียญทอง</h3>
                  <div class="price-info">
                    <span class="price-text">ราคาซื้อ: {{ purchasePriceInfo }}</span>
                    <span class="tips-text">กรุณาเลือกจำนวนเหรียญทองที่ต้องการซื้อ</span>
                  </div>
                </div>
                <button 
                  class="custom-service-btn" 
                  @click="showCustomerServiceDialog"
                  type="button"
                  disabled
                >
                  <span class="service-icon">บริการลูกค้า</span>
                </button>
              </div>
              <!-- 快捷金额选择 -->
              <div class="quick-amounts">
                <button
                  v-for="amount in quickAmounts"
                  :key="amount"
                  @click="selectQuickAmount(amount)"
                  :class="[
                    'amount-btn',
                    { 'amount-btn-active': rechargeForm.amount === amount * 5.5 }
                  ]"
                  type="button"
                >
                  <div class="btn-content">
                    <div class="coin-amount">{{ amount }}M</div>
                    <div class="price-amount">{{ (amount * 5.5).toFixed(1) }}฿</div>
                  </div>
                </button>
              </div>
              
              <!-- 金额显示框（只读） -->
              <div class="amount-display-container">
                <input
                  v-model.number="rechargeForm.amount"
                  type="number"
                  readonly
                  placeholder="กรุณาเลือกจำนวนเงินที่ต้องการเติม"
                  class="custom-amount-input readonly-input"
                />
                <div class="currency-label">THB</div>
              </div>
            </div>
          </el-form-item>

          <!-- 用户UID -->
          <el-form-item prop="userId" class="user-id-form-item">
            <div class="form-section">
              <div class="label-with-help">
                <label class="section-label">ไอดี</label>
                <button 
                  class="help-icon" 
                  @click="toggleHelpTooltip"
                  @mouseenter="showHelpTooltip"
                  @mouseleave="hideHelpTooltip"
                  type="button"
                >
                  ?
                </button>
              </div>
              <div class="input-with-tooltip">
                <input
                  v-model="rechargeForm.userId"
                  type="text"
                  placeholder="กรุณาใส่ไอดีเกมของคุณ"
                  class="custom-user-input"
                />
                <div 
                  v-if="showTooltip" 
                  class="custom-tooltip"
                >
                  กรุณากรอกรหัสเกมให้ถูกต้อง
                </div>
              </div>
            </div>
          </el-form-item>

          <!-- 支付方式 -->
          <el-form-item class="payment-method-form-item">
            <div class="form-section">
              <label class="section-label">วิธีการชำระเงิน</label>
              <div class="simple-payment-container">
                <img :src="promptPayImage" alt="PromptPay" class="simple-promptpay-logo" />
              </div>
            </div>
          </el-form-item>

          <!-- 提交按钮 -->
          <el-form-item class="submit-form-item">
            <el-button
              type="primary"
              size="large"
              @click="handleSubmitRecharge"
              :loading="submitting"
              :disabled="!isFormValid"
              class="submit-btn"
            >
              <template v-if="!submitting">
                ยืนยันการซื้อเหรียญทอง
              </template>
              <template v-else>
                {{ submitButtonText }}
              </template>
            </el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <!-- 充值成功对话框 -->
    <RechargeSuccessDialog
      v-model="showSuccessDialog"
      :recharge-data="successData"
      @close="handleSuccessClose"
    />

    <!-- 客服确认对话框 -->
    <div v-if="showServiceDialog" class="custom-dialog-overlay" @click="hideCustomerServiceDialog">
      <div class="custom-dialog" @click.stop>
        <div class="dialog-header">
          <h3>ติดต่อบริการลูกค้า</h3>
          <button class="close-btn" @click="hideCustomerServiceDialog">×</button>
        </div>
        <div class="dialog-body">
          <p>คุณกำลังจะไปยังหน้าบริการลูกค้า ต้องการดำเนินการต่อหรือไม่？</p>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="hideCustomerServiceDialog">ยกเลิก</button>
          <button class="confirm-btn" @click="goToCustomerService">ยืนยัน</button>
        </div>
      </div>
    </div>

    <!-- 网络错误对话框 -->
    <div v-if="showNetworkErrorDialog" class="custom-dialog-overlay" @click="hideNetworkErrorDialog">
      <div class="custom-dialog" @click.stop>
        <div class="dialog-header">
          <h3>เครือข่ายมีปัญหา</h3>
          <button class="close-btn" @click="hideNetworkErrorDialog">×</button>
        </div>
        <div class="dialog-body">
          <p>เครือข่ายมีปัญหา กรุณาลองใหม่อีกครั้งในภายหลัง</p>
        </div>
        <div class="dialog-footer">
          <button class="confirm-btn single-btn" @click="hideNetworkErrorDialog">ยืนยัน</button>
        </div>
      </div>
    </div>

    <!-- 现有充值记录对话框 -->
    <div v-if="showExistingDialog" class="custom-dialog-overlay" @click="hideExistingDialog">
      <div class="custom-dialog" @click.stop>
        <div class="dialog-header">
          <h3>ตรวจพบคำสั่งซื้อที่มีอยู่</h3>
          <button class="close-btn" @click="hideExistingDialog">×</button>
        </div>
        <div class="dialog-body">
          <div class="existing-order-info">
            <p class="order-id">หมายเลขคำสั่งซื้อ: {{ existingRecord?.orderId }}</p>
            <p class="order-amount">จำนวนเงิน: {{ existingRecord?.amount }} ฿</p>
            <p class="wait-time">จำนวนเงินนี้สามารถเติมเงินครั้งถัดไปใน: <span class="countdown">{{ formatRemainingTime }}</span></p>
          </div>
          <p class="description">
            คุณได้สร้างคำสั่งซื้อเติมเงิน {{ existingRecord?.amount }} ฿ แล้วใน 15 นาทีที่ผ่านมา<br>
            คุณสามารถเลือกจำนวนเงินอื่น หรือใช้ลิงก์ชำระเงินที่มีอยู่
          </p>
        </div>
        <div class="dialog-footer">
          <button class="cancel-btn" @click="hideExistingDialog">ปิด</button>
          <button class="confirm-btn" @click="continueWithExistingOrder">ไปยังหน้าชำระเงิน</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import { useToast } from 'vue-toastification'
import type { FormInstance, FormRules } from 'element-plus'
import {
  Loading
} from '@element-plus/icons-vue'
import { trpc } from '../utils/trpc'
import RechargeSuccessDialog from '../components/RechargeSuccessDialog.vue'
import promptPayImage from '@/assets/prompPay.png'

// 路由和工具
const route = useRoute()
const toast = useToast()

// 响应式数据
const loading = ref(true)
const error = ref('')
const submitting = ref(false)
const showSuccessDialog = ref(false)
const showServiceDialog = ref(false)
const showNetworkErrorDialog = ref(false)
const showTooltip = ref(false)
const showExistingDialog = ref(false)
const existingRecord = ref<RechargeRecord | null>(null)
const remainingTime = ref(0)
const countdownInterval = ref<NodeJS.Timeout>()
const rechargeFormRef = ref<FormInstance>()
const sessionData = ref<any>(null)
const successData = ref<any>(null)
const submitButtonText = ref('กำลังประมวลผล...')
const retryAttempt = ref(0)
const maxRetries = ref(2)

// 环境变量配置
const customerServiceUrl = (import.meta as any).env.VITE_CUSTOMER_SERVICE_URL || 'https://t.me/your_customer_service'

// 充值记录接口
interface RechargeRecord {
  userId: string;
  orderId: string;
  amount: number;
  paymentUrl: string;
  timestamp: number;
  sessionId: string;
}

// 获取存储键名（基于用户ID和金额）
const getStorageKey = (userId: string, amount: number) => `recharge_record_${userId}_${amount}`;

// 检查指定金额是否有15分钟内的充值记录
function checkRecentRecharge(userId: string, amount: number): RechargeRecord | null {
  const storageKey = getStorageKey(userId, amount);
  const recordStr = localStorage.getItem(storageKey);

  if (!recordStr) return null;

  try {
    const record: RechargeRecord = JSON.parse(recordStr);
    const now = Date.now();
    const timeDiff = now - record.timestamp;
    const fifteenMinutes = 15 * 60 * 1000; // 15分钟

    // 检查是否在15分钟内
    if (timeDiff <= fifteenMinutes) {
      return record;
    } else {
      // 超过15分钟，清除记录
      localStorage.removeItem(storageKey);
      return null;
    }
  } catch (error) {
    // 数据格式错误，清除记录
    localStorage.removeItem(storageKey);
    return null;
  }
}

// 保存充值记录（基于用户ID和金额）
function saveRechargeRecord(userId: string, orderId: string, amount: number, paymentUrl: string, sessionId: string) {
  const record: RechargeRecord = {
    userId,
    orderId,
    amount,
    paymentUrl,
    timestamp: Date.now(),
    sessionId
  };

  const storageKey = getStorageKey(userId, amount);
  localStorage.setItem(storageKey, JSON.stringify(record));
}

// 获取剩余等待时间（毫秒）
function getRemainingWaitTime(record: RechargeRecord): number {
  const now = Date.now();
  const elapsed = now - record.timestamp;
  const fifteenMinutes = 15 * 60 * 1000;
  return Math.max(0, fifteenMinutes - elapsed);
}

// 快捷金额选项 (从服务器动态加载)
const quickAmounts = ref<number[]>([100, 500, 1000, 2000, 5000, 10000])


// 购买价格信息 (从服务器动态加载)
const purchasePriceInfo = ref<string>('5.5泰铢=1M金币')

// 表单数据
const rechargeForm = ref({
  amount: null as number | null,
  userId: '',
  paymentMethod: 'qrPay' as 'qrPay' | 'BankTransfer'
})

// 表单验证规则
const rechargeRules = computed<FormRules>(() => ({
  amount: [
    { required: true, message: 'กรุณาใส่จำนวนเงินเติม', trigger: 'blur' },
    { 
      validator: (_rule: any, value: any, callback: any) => {
        if (!value || value <= 0) {
          callback(new Error('กรุณาใส่จำนวนเงินเติมที่ถูกต้อง'))
        } else if (value > 100000) {
          callback(new Error('จำนวนเงินเติมต้องไม่เกิน 100,000'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ],
  userId: [
    { required: true, message: 'กรุณาใส่ไอดีผู้ใช้', trigger: 'blur' }, // 提交时必填
    { min: 1, message: 'ไอดีไม่สามารถเว้นว่างได้', trigger: 'blur' }
  ]
}))

// 计算属性
const isFormValid = computed(() => {
  const amount = parseFloat(rechargeForm.value.amount as any)
  return amount &&
         amount > 0 &&
         amount <= 100000 &&
         rechargeForm.value.userId &&
         rechargeForm.value.userId.trim().length > 0
  // 充值时UID必填
})

// 生成默认值的工具函数
function generateBankCardNumber(): string {
  let cardNumber = ''
  for (let i = 0; i < 16; i++) {
    cardNumber += Math.floor(Math.random() * 10).toString()
  }
  return cardNumber
}

// 移除getDefaultBankCode函数，不再需要

// 加载会话数据
async function loadSessionData() {
  try {
    loading.value = true
    error.value = ''
    
    const sessionId = route.params.sessionId as string
    if (!sessionId) {
      throw new Error('ขาดรหัสเซสชัน')
    }

    // 从URL查询参数获取基本信息（改为可选）
    const appid = route.query.appid as string
    const saasId = route.query.saasId as string
    const username = route.query.username as string

    // 只有sessionId是必须的，其他参数可选
    if (!sessionId) {
      throw new Error('ขาดรหัสเซสชัน')
    }

    // 设置会话数据
    sessionData.value = {
      sessionId,
      appid: appid || '', // 提供默认值
      saasId: saasId || '', // 提供默认值
      username: username || '用户', // 提供默认值
      extractedUserId: appid ? extractUserIdFromAppId(appid) : null
    }

    // 只有在能提取到UID时才自动填充
    if (sessionData.value.extractedUserId) {
      rechargeForm.value.userId = sessionData.value.extractedUserId
    }

    // 加载快捷金额配置和购买价格信息
    await Promise.all([
      loadQuickAmounts(),
      loadPurchasePriceInfo()
    ])

  } catch (err) {
    console.error('Failed to load session data:', err)
    error.value = err instanceof Error ? err.message : 'โหลดไม่สำเร็จ'
  } finally {
    loading.value = false
  }
}

// 从appid提取用户ID（前端版本）
function extractUserIdFromAppId(appid: string): string | null {
  const match = appid.match(/\/start\s+(\d+)/)
  if (match && match[1]) {
    return match[1]
  }
  
  const numberMatch = appid.match(/(\d+)/)
  if (numberMatch && numberMatch[1]) {
    return numberMatch[1]
  }
  
  return null
}

// 移除loadAvailableChannels函数，不再需要加载渠道列表

// 加载快捷金额配置
async function loadQuickAmounts() {
  try {
    const result = await trpc.recharge.getPublicQuickAmounts.query()
    
    if (result.success) {
      quickAmounts.value = result.data.amounts || [100, 500, 1000, 2000, 5000, 10000]
    } else {
      console.warn('Failed to load quick amounts config, using default values')
    }
  } catch (err) {
    console.warn('Failed to load quick amounts config, using default values:', err)
  }
}


// 加载购买价格信息配置
async function loadPurchasePriceInfo() {
  try {
    const result = await trpc.recharge.getPublicPurchasePriceInfo.query()
    
    if (result.success) {
      purchasePriceInfo.value = result.data.priceInfo || '5.5泰铢=1M金币'
    } else {
      console.warn('Failed to load purchase price info config, using default value')
    }
  } catch (err) {
    console.warn('Failed to load purchase price info config, using default value:', err)
  }
}

// 快捷金额选择
function selectQuickAmount(amount: number) {
  // 将金币数量转换为泰铢价格：金币数量 × 5.5
  const thbAmount = amount * 5.5
  rechargeForm.value.amount = thbAmount
}

// 移除handleChannelChange函数，不再需要

// 更新loading文本的函数
function updateSubmitButtonText(attempt: number, isRetrying: boolean = false) {
  if (attempt === 1 && !isRetrying) {
    submitButtonText.value = 'กำลังประมวลผลคำขอเติมเงิน...'
  } else if (isRetrying) {
    submitButtonText.value = `กำลังค้นหาช่องทางชำระเงินที่ดีที่สุดสำหรับคุณ... (${attempt}/${maxRetries.value + 1})`
  } else {
    submitButtonText.value = 'กำลังสร้างคำสั่งซื้อสำหรับการชำระเงิน...'
  }
}

// 第三方回调成功后的额外处理 - 执行售卡并发送Telegram通知
async function handleThirdPartyCallbackSuccess(orderId: string) {
  console.log('Third party callback success, executing card sell and notification for order:', orderId)

  try {
    // 执行售卡并发送Telegram通知到SaaS系统
    const result = await trpc.recharge.executeCardSellAndNotify.mutate({
      orderId: orderId
    })

    if (result.success) {
      if (result.data.sellCardSuccess) {
        console.log('✅ 自动售卡成功:', {
          orderId,
          message: result.data.message,
          telegramSent: result.data.telegramSent
        })
      } else {
        console.warn('⚠️ 自动售卡失败，已通知手动处理:', {
          orderId,
          message: result.data.message,
          telegramSent: result.data.telegramSent
        })
      }
    } else {
      console.error('❌ 售卡流程失败:', result.message)
    }
  } catch (error) {
    console.error('执行售卡流程异常:', error)
    // 即使售卡流程失败，也不影响用户的充值成功体验
    // 这里可以选择静默失败或者显示警告信息
  }
}

// 提交充值
async function handleSubmitRecharge() {
  if (!rechargeFormRef.value) return

  try {
    await rechargeFormRef.value.validate()
    
    const userId = rechargeForm.value.userId;
    const amount = rechargeForm.value.amount!;

    // 🔍 检查当前金额是否有最近的充值记录
    const recentRecord = checkRecentRecharge(userId, amount);
    
    if (recentRecord) {
      // 显示现有充值记录
      showExistingRechargeDialog(recentRecord);
      return;
    }
    
    submitting.value = true
    retryAttempt.value = 0
    updateSubmitButtonText(1)

    // 构建充值请求数据（不指定渠道，由后端自动选择）
    const rechargeData = {
      userId: parseInt(rechargeForm.value.userId),
      amount: parseFloat(rechargeForm.value.amount as any),
      // paymentChannel: 不指定，让后端自动选择最优渠道
      paymentMethod: rechargeForm.value.paymentMethod,
      paymentName: sessionData.value?.username || '用户',
      transAccNo: generateBankCardNumber(),
      bankCode: '001', // 默认银行编码，后端会根据选择的渠道调整
      customerEmail: 'user@example.com',
      customerPhone: '+66123456789',
      extendParam: `SessionId: ${sessionData.value?.sessionId}`,
      sessionId: sessionData.value?.sessionId || ''
    }

    console.log('Submitting recharge data:', rechargeData)

    // 监听重试进度（模拟，实际后端重试用户无感知）
    const progressInterval = setInterval(() => {
      retryAttempt.value++
      if (retryAttempt.value <= maxRetries.value) {
        updateSubmitButtonText(retryAttempt.value, true)
      }
    }, 2000)

    try {
      const result = await trpc.recharge.userRechargeCreate.mutate(rechargeData)
      clearInterval(progressInterval)

      if (result.success) {
        // 成功处理
        submitButtonText.value = 'สร้างคำสั่งซื้อเติมเงินสำเร็จ！'

        const { rechargeRecord, paymentResponse, selectedChannel, retryHistory } = result.data || {}
        const orderId = rechargeRecord?.orderId

        if (!orderId) {
          console.error('⛔️ 充值创建成功但缺少订单号，无法继续后续流程', { apiResponse: result })
          toast.error('ระบบผิดปกติ กรุณาลองใหม่อีกครั้ง')
          return
        }

        const normalizedPaymentResponse = paymentResponse || {}
        const paymentUrl = normalizedPaymentResponse.payUrl || normalizedPaymentResponse.qrCodeUrl

        // 💾 保存充值记录到 localStorage
        if (paymentUrl) {
          saveRechargeRecord(
            rechargeForm.value.userId,
            orderId,
            rechargeForm.value.amount!,
            paymentUrl,
            sessionData.value?.sessionId || ''
          );
        }

        successData.value = {
          orderId,
          amount: rechargeForm.value.amount,
          userId: rechargeForm.value.userId,
          paymentChannel: selectedChannel || rechargeRecord?.paymentChannel || 'AUTO',
          paymentResponse: normalizedPaymentResponse,
          retryHistory: retryHistory || []
        }

        // 如果有重试历史，显示智能重试成功的提示
        if (retryHistory && retryHistory.length > 1) {
          const successfulAttempt = retryHistory.find((h: any) => h.success)
          if (successfulAttempt) {
            toast.success(`เปลี่ยนช่องทางชำระเงินอัตโนมัติสำเร็จ！ ครั้งที่ ${successfulAttempt.attempt} สำเร็จ`)
          }
        }

        console.log('✅ 成功创建充值订单，等待支付', {
          orderId,
          selectedChannel: selectedChannel || rechargeRecord?.paymentChannel,
          retryCount: retryHistory?.length || 0,
          paymentResponse: normalizedPaymentResponse
        })

        showSuccessDialog.value = true

        // 调用第三方回调成功占位接口
        await handleThirdPartyCallbackSuccess(orderId)

        // 如果有支付URL，在新窗口打开
        if (paymentUrl) {
          window.open(paymentUrl, '_blank')
        }

      } else {
        console.warn('❌ 创建充值订单失败', { apiResponse: result })
        // 检查是否是网络繁忙错误（所有渠道都失败）
        if (result.message && (result.message.includes('网络繁忙') || result.message.includes('渠道') || result.message.includes('支付'))) {
          showNetworkErrorDialog.value = true
        } else {
          toast.error(result.message || 'สร้างการเติมเงินไม่สำเร็จ')
        }
      }
    } catch (apiError) {
      clearInterval(progressInterval)
      console.error('调用 userRechargeCreate 接口异常', apiError)
      throw apiError
    }
    
  } catch (err) {
    console.error('Recharge submission failed:', err)
    
    // 智能错误处理
    if (err instanceof Error) {
      if (err.message.includes('网络繁忙') || err.message.includes('稍后重试') || err.message.includes('渠道') || err.message.includes('支付')) {
        showNetworkErrorDialog.value = true
      } else if (err.message.includes('validation') || err.message.includes('验证')) {
        toast.error('กรุณาตรวจสอบข้อมูลที่กรอกให้ถูกต้อง')
      } else {
        showNetworkErrorDialog.value = true
      }
    } else {
      showNetworkErrorDialog.value = true
    }
  } finally {
    submitting.value = false
    retryAttempt.value = 0
    submitButtonText.value = 'กำลังประมวลผล...'
  }
}

// 充值成功对话框关闭处理
function handleSuccessClose() {
  showSuccessDialog.value = false
  // 可以选择重置表单或跳转到其他页面
  rechargeForm.value = {
    amount: null,
    userId: '',
    paymentMethod: 'qrPay'
  }
}

// 客服相关方法
function showCustomerServiceDialog() {
  showServiceDialog.value = true
}

function hideCustomerServiceDialog() {
  showServiceDialog.value = false
}

function goToCustomerService() {
  hideCustomerServiceDialog()
  window.open(customerServiceUrl, '_blank')
}

// 帮助提示相关方法
function showHelpTooltip() {
  showTooltip.value = true
}

function hideHelpTooltip() {
  showTooltip.value = false
}

function toggleHelpTooltip() {
  showTooltip.value = !showTooltip.value
}

// 网络错误弹框相关方法
function hideNetworkErrorDialog() {
  showNetworkErrorDialog.value = false
}

// 显示现有充值记录对话框
function showExistingRechargeDialog(record: RechargeRecord) {
  existingRecord.value = record;
  remainingTime.value = getRemainingWaitTime(record);
  showExistingDialog.value = true;
  
  // 开始倒计时
  startCountdown();
}

// 倒计时功能
function startCountdown() {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
  
  countdownInterval.value = setInterval(() => {
    if (existingRecord.value) {
      remainingTime.value = getRemainingWaitTime(existingRecord.value);
      
      if (remainingTime.value <= 0) {
        // 时间到了，可以重新充值
        clearInterval(countdownInterval.value!);
        showExistingDialog.value = false;
        // 清除记录
        localStorage.removeItem(getStorageKey(existingRecord.value.userId, existingRecord.value.amount));
      }
    }
  }, 1000);
}

// 格式化剩余时间
const formatRemainingTime = computed(() => {
  const minutes = Math.floor(remainingTime.value / (60 * 1000));
  const seconds = Math.floor((remainingTime.value % (60 * 1000)) / 1000);
  return `${minutes}นาที${seconds}วินาที`;
});

// 继续使用现有订单
function continueWithExistingOrder() {
  if (existingRecord.value?.paymentUrl) {
    window.open(existingRecord.value.paymentUrl, '_blank');
  }
  showExistingDialog.value = false;
}

// 隐藏现有订单对话框
function hideExistingDialog() {
  showExistingDialog.value = false;
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
}

// 页面加载时执行
onMounted(() => {
  loadSessionData()
})

// 组件卸载时清理定时器
onUnmounted(() => {
  if (countdownInterval.value) {
    clearInterval(countdownInterval.value);
  }
})
</script>

<style scoped>
.user-recharge-container {
  min-height: 100vh;
  background: #f8fafc;
  padding: 8px;
  box-sizing: border-box;
}

.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.loading-content {
  text-align: center;
  padding: 40px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.loading-icon {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 20px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.recharge-form-container {
  max-width: 100%;
  margin: 0 auto;
  padding: 0;
}

.recharge-form {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  margin: 0;
  display: flex;
  flex-direction: column;
}

.simple-form {
  width: 100%;
  display: flex;
  flex-direction: column;
  gap: 0;
}

.form-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: stretch;
  margin: 0;
  padding: 0;
}

.section-title-wrapper {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 12px;
}

.title-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: #1a202c;
  margin: 0;
  text-align: left;
}

.price-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.price-text {
  font-size: 14px;
  color: #f56c6c;
  font-weight: 500;
}

.tips-text {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.4;
}

.custom-service-btn {
  background: none;
  border: 1px solid #e5e7eb;
  border-radius: 20px;
  padding: 8px 14px;
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  color: #6b7280;
  display: flex;
  align-items: center;
  gap: 4px;
  height: fit-content;
  white-space: nowrap;
  flex-shrink: 0;
}

.custom-service-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
  background: #f0f9ff;
}

.custom-service-btn:disabled {
  background: #f9fafb;
  border-color: #e5e7eb;
  color: #9ca3af;
  cursor: not-allowed;
  opacity: 0.6;
}

.custom-service-btn:disabled:hover {
  border-color: #e5e7eb;
  color: #9ca3af;
  background: #f9fafb;
}

.service-icon {
  font-size: 12px;
}

.label-with-help {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}

.section-label {
  display: block;
  font-size: 16px;
  font-weight: 500;
  color: #374151;
  margin: 0;
  text-align: left;
}

.help-icon {
  width: 18px;
  height: 18px;
  border-radius: 50%;
  background: #f3f4f6;
  border: 1px solid #d1d5db;
  color: #6b7280;
  font-size: 12px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.help-icon:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
}

.input-with-tooltip {
  position: relative;
}

.custom-tooltip {
  position: absolute;
  top: -35px;
  left: 50%;
  transform: translateX(-50%);
  background: #374151;
  color: white;
  padding: 6px 10px;
  border-radius: 6px;
  font-size: 12px;
  white-space: nowrap;
  z-index: 1000;
  opacity: 0.9;
}

.custom-tooltip::after {
  content: '';
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  border: 4px solid transparent;
  border-top-color: #374151;
}

.amount-form-item {
  margin-bottom: 20px;
}

.amount-display-container {
  position: relative;
  width: 100%;
  margin-top: 12px;
}

.custom-amount-input {
  width: 100%;
  height: 44px;
  padding: 0 60px 0 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 16px;
  background: white;
  outline: none;
  transition: all 0.2s ease;
}

.custom-amount-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.custom-amount-input::placeholder {
  color: #9ca3af;
}

.readonly-input {
  background-color: #f9fafb !important;
  cursor: default !important;
  user-select: none;
}

.readonly-input:focus {
  border-color: #e5e7eb !important;
  box-shadow: none !important;
}

.currency-label {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #6b7280;
  font-weight: 500;
  pointer-events: none;
  font-size: 14px;
}

.quick-amounts {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 12px;
  margin-top: 0;
  margin-bottom: 0;
  width: 100%;
  box-sizing: border-box;
  padding: 0;
  margin-left: 0;
  margin-right: 0;
}

.amount-btn {
  height: 46px;
  border-radius: 8px;
  font-weight: 500;
  border: 2px solid #e5e7eb;
  background: white;
  color: #374151;
  transition: all 0.2s ease;
  width: 100%;
  min-width: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  cursor: pointer;
  font-size: 13px;
  margin: 0;
  padding: 6px 4px;
  outline: none;
}

.btn-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.coin-amount {
  font-size: 13px;
  font-weight: 600;
  line-height: 1;
}

.price-amount {
  font-size: 10px;
  opacity: 0.8;
  line-height: 1;
}

.amount-btn:hover {
  border-color: #3b82f6;
  color: #3b82f6;
}

.amount-btn-active {
  background: #3b82f6 !important;
  border-color: #3b82f6 !important;
  color: white !important;
}

.amount-btn-active:hover {
  background: #2563eb !important;
  border-color: #2563eb !important;
}

.user-id-form-item {
  margin-bottom: 18px;
}

.custom-user-input {
  width: 100%;
  height: 44px;
  padding: 0 16px;
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  font-size: 16px;
  background: white;
  outline: none;
  transition: all 0.2s ease;
}

.custom-user-input:focus {
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.custom-user-input::placeholder {
  color: #9ca3af;
}

.payment-method-form-item {
  margin-bottom: 20px;
}

.simple-payment-container {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 8px;
}

.simple-promptpay-logo {
  height: 50px;
  width: auto;
  object-fit: contain;
}

.payment-name {
  font-size: 16px;
  font-weight: 500;
  color: #374151;
}

.submit-form-item {
  margin-bottom: 0;
  margin-top: 16px;
}

.submit-btn {
  width: 100%;
  height: 48px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 12px;
  background: #3b82f6;
  border-color: #3b82f6;
  transition: all 0.2s ease;
}

.submit-btn:hover {
  background: #2563eb;
  border-color: #2563eb;
  transform: translateY(-1px);
  box-shadow: 0 8px 25px rgba(59, 130, 246, 0.3);
}

.submit-btn:active {
  transform: translateY(0);
}


/* 自定义对话框样式 */
.custom-dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.custom-dialog {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.dialog-header {
  padding: 20px 20px 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1a202c;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  color: #9ca3af;
  cursor: pointer;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: #f3f4f6;
  color: #6b7280;
}

.dialog-body {
  padding: 20px;
}

.dialog-body p {
  margin: 0;
  color: #4b5563;
  line-height: 1.5;
  text-align: center;
}

.dialog-footer {
  padding: 0 20px 20px 20px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.cancel-btn, .confirm-btn {
  padding: 8px 20px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s ease;
  border: 1px solid transparent;
}

.cancel-btn {
  background: #f9fafb;
  color: #6b7280;
  border-color: #e5e7eb;
}

.cancel-btn:hover {
  background: #f3f4f6;
  border-color: #d1d5db;
}

.confirm-btn {
  background: #3b82f6;
  color: white;
  border-color: #3b82f6;
}

.confirm-btn:hover {
  background: #2563eb;
  border-color: #2563eb;
}

.single-btn {
  width: 100%;
}

/* 现有订单信息样式 */
.existing-order-info {
  background: #f8fafc;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  border-left: 4px solid #3b82f6;
}

.existing-order-info p {
  margin: 8px 0;
  font-size: 14px;
  line-height: 1.5;
}

.order-id {
  font-weight: 600;
  color: #1e40af;
}

.order-amount {
  font-weight: 600;
  color: #059669;
}

.wait-time {
  color: #dc2626;
  font-weight: 500;
}

.countdown {
  font-weight: 700;
  color: #dc2626;
  background: #fef2f2;
  padding: 2px 6px;
  border-radius: 4px;
}

.description {
  color: #6b7280;
  font-size: 13px;
  line-height: 1.6;
  text-align: center;
  margin: 0;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .user-recharge-container {
    padding: 6px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  .recharge-form-container {
    max-width: 100%;
    display: flex;
    flex-direction: column;
  }
  
  .recharge-form {
    padding: 12px;
    margin: 0;
    display: flex;
    flex-direction: column;
  }
  
  .simple-form {
    display: flex;
    flex-direction: column;
    gap: 0;
  }
  
  .section-title-wrapper {
    margin-bottom: 12px;
    gap: 8px;
  }
  
  .section-title {
    font-size: 18px;
  }
  
  .price-text {
    font-size: 12px;
  }
  
  .tips-text {
    font-size: 11px;
  }
  
  .custom-service-btn {
    padding: 4px 8px;
    font-size: 10px;
  }
  
  .custom-service-btn:disabled {
    background: #f9fafb;
    border-color: #e5e7eb;
    color: #9ca3af;
    cursor: not-allowed;
    opacity: 0.6;
  }
  
  .amount-form-item {
    margin-bottom: 16px;
  }
  
  .amount-input-container {
    margin-bottom: 8px;
  }
  
  .quick-amounts {
    grid-template-columns: repeat(3, 1fr);
    gap: 6px;
    width: 100%;
    margin-top: 8px;
  }
  
  .amount-btn {
    height: 42px;
    font-size: 12px;
    width: 100%;
    border-radius: 6px;
    font-weight: 500;
    min-width: 0;
    box-sizing: border-box;
    padding: 4px 2px;
  }
  
  .coin-amount {
    font-size: 12px;
  }
  
  .price-amount {
    font-size: 9px;
  }
  
  .amount-btn-active {
    background: #3b82f6 !important;
    border-color: #3b82f6 !important;
    color: white !important;
    font-weight: 600;
  }
  
  .user-id-form-item {
    margin-bottom: 16px;
  }
  
  .section-label {
    font-size: 14px;
    margin-bottom: 6px;
  }
  
  .custom-user-input {
    height: 42px;
    border-radius: 8px;
    font-size: 16px;
  }
  
  .payment-method-form-item {
    margin-bottom: 16px;
  }
  
  .payment-method-container {
    padding: 10px;
    border-radius: 8px;
    margin-top: 6px;
  }
  
  .promptpay-option {
    justify-content: center;
  }
  
  .payment-name {
    font-size: 15px;
    font-weight: 600;
  }
  
  .submit-form-item {
    margin-top: 16px;
    padding-top: 0;
  }
  
  .submit-btn {
    height: 46px;
    font-size: 16px;
    border-radius: 10px;
    font-weight: 600;
  }
  
  .custom-amount-input {
    height: 42px;
    border-radius: 8px;
    font-size: 16px;
    padding-right: 55px;
  }
  
  .currency-label {
    font-size: 12px;
  }
  
  .amount-display-container {
    margin-top: 8px;
  }
}

@media (max-width: 480px) {
  .user-recharge-container {
    padding: 4px;
    min-height: 100vh;
    display: flex;
    flex-direction: column;
  }
  
  .recharge-form-container {
    display: flex;
    flex-direction: column;
  }
  
  .recharge-form {
    padding: 10px;
    display: flex;
    flex-direction: column;
  }
  
  .simple-form {
    display: flex;
    flex-direction: column;
    gap: 0;
  }
  
  .section-title-wrapper {
    margin-bottom: 10px;
  }
  
  .section-title {
    font-size: 16px;
  }
  
  .price-text {
    font-size: 11px;
  }
  
  .tips-text {
    font-size: 10px;
  }
  
  .custom-service-btn {
    padding: 3px 6px;
    font-size: 9px;
  }
  
  .custom-service-btn:disabled {
    background: #f9fafb;
    border-color: #e5e7eb;
    color: #9ca3af;
    cursor: not-allowed;
    opacity: 0.6;
  }
  
  .help-icon {
    width: 16px;
    height: 16px;
    font-size: 10px;
  }
  
  .amount-form-item {
    margin-bottom: 12px;
  }
  
  .user-id-form-item {
    margin-bottom: 12px;
  }
  
  .payment-method-form-item {
    margin-bottom: 12px;
  }
  
  .custom-amount-input {
    height: 40px;
    border-radius: 6px;
    font-size: 15px;
    padding-right: 50px;
  }
  
  .custom-user-input {
    height: 40px;
    border-radius: 6px;
    font-size: 15px;
  }
  
  .currency-label {
    font-size: 11px;
    right: 12px;
  }
  
  .quick-amounts {
    gap: 4px;
    margin-top: 6px;
  }
  
  .amount-btn {
    height: 38px;
    font-size: 11px;
    border-radius: 5px;
    padding: 3px 2px;
  }
  
  .coin-amount {
    font-size: 11px;
  }
  
  .price-amount {
    font-size: 8px;
  }
  
  .payment-method-container {
    padding: 8px;
  }
  
  .payment-name {
    font-size: 14px;
  }
  
  .submit-form-item {
    margin-top: 12px;
    padding-top: 0;
  }
  
  .submit-btn {
    height: 44px;
    font-size: 15px;
    border-radius: 8px;
  }
  
  .amount-display-container {
    margin-top: 6px;
  }
  
  .custom-dialog {
    width: 95%;
    max-width: 350px;
  }
  
  .dialog-header h3 {
    font-size: 16px;
  }
  
  .dialog-footer {
    flex-direction: column;
  }
  
  .cancel-btn, .confirm-btn {
    width: 100%;
    padding: 12px;
  }
}
</style>
